package com.juyu.miliao.scheduler.service;

import com.juyu.miliao.common.netease.NetEaseCloudUserService;
import com.juyu.miliao.scheduler.cache.RobotMessageCache;
import com.juyu.miliao.scheduler.dao.mysql.UserInfoDao;
import com.juyu.miliao.scheduler.dao.redis.LineTimeRedisDao;
import com.juyu.miliao.scheduler.domin.RobotMessage;
import com.juyu.miliao.scheduler.domin.User;
import com.juyu.miliao.scheduler.domin.UserWallet;
import net.sf.json.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 1.1机器人消息
 * by wbf
 * 2019-05-15 复查慢查询sql 发现已弃用该定时任务
 */
@Component
public class RobotMessageService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private UserInfoDao userInfoDao;
    @Resource
    private LineTimeRedisDao lineTimeRedisDao;
    private final Logger logger = LoggerFactory.getLogger(RobotMessageService.class);

//    @Scheduled(fixedDelay = 1000 * 10, initialDelay = 1000 * 30)
    public void scheduler(){
        logger.info("定时任务RobotMessageService开始：time={}",
                LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        //获取任务池数据
        Map<Object, Object> map = stringRedisTemplate.opsForHash().entries("robotMessageScheduled");
        //获取当前时间戳
        Instant nowTime = Instant.now();
        long timestamp = nowTime.toEpochMilli();// 精确到毫秒
        map.forEach((key, value) -> {
            String str = key.toString();
            str = str.substring(0,str.length()-4);
            if(Long.parseLong(str) < timestamp){
                JSONObject jasonObject = JSONObject.fromObject(value.toString());
                Map jsonMap = (Map) jasonObject;
                int type = Integer.parseInt(jsonMap.get("type").toString());
                int userId = Integer.parseInt(jsonMap.get("userId").toString());
                int packageId = Integer.parseInt(jsonMap.get("packageId").toString());
                User user = userInfoDao.findUserById(userId);
                //用户为空,缓存出错 清除缓存
                if (user == null) {
                    stringRedisTemplate.opsForHash().delete("robotMessageScheduled", key.toString());
                    return;
                }
                try {
                    //ext开发者扩展字段-type类型：1文字，2免费图片，3付费图片，4视频
                    switch (type){
                        case 1:
                            textMessage(userId,packageId);
                            break;
                        case 2:
                            pictureMessage(userId,2,packageId);
                            break;
                        case 3:
                            pictureMessage(userId,3,packageId);
                            break;
                        case 4:
                            videoMessage(user,packageId);
                            break;
                        case 5:
                            vestTCYLVideoMessage(user,packageId);
                            break;
                    }
                    //删除已发送redis数据
                    stringRedisTemplate.opsForHash().delete("robotMessageScheduled", key.toString());
                }catch (Exception e) {
                    logger.info("机器人消息error：type错误========key={}----value={}-----error{}",key.toString(),value.toString(),e);
                }
            }
        });
        logger.info("定时任务RobotMessageService结束：time={}",
                LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
    }

    private void textMessage(int userId,int packageId){
        //随机获取要发送的内容
        List<RobotMessage> textList = RobotMessageCache.INSTANCE.getRobotMessageList(1,packageId);
        JSONObject body = new JSONObject();
        body.put("msg", textList.get((int) (Math.random() * textList.size())).getMessage());
        //获取一个随机主播
        List<Integer> userIds = new ArrayList<>();
        List<User> userList = userInfoDao.getUserListRand(5, userIds);
        User user = userList.get((int) (Math.random() * userList.size()));
        //开发者扩展字段
        JSONObject ext = new JSONObject();
        try {
            logger.info("发送文字-云信：userId={},message={}", userId, body.toString());
            String temp = NetEaseCloudUserService.getSendMsg(userId,user.getUserId(), 0, body.toString(),ext.toString(),"");
            if (!temp.substring(temp.indexOf("code") + 6, temp.indexOf("code") + 9).equals("200"))
                logger.error("发送普通消息异常-云信：userId={},message={}", userId, temp);
        } catch (Exception e) {
            logger.error("发送普通消息异常：userId={},error={}", userId, e);
        }
    }

    private void pictureMessage(int userId,int type,int packageId){
        //随机获取要发送的内容
        List<RobotMessage> picList = RobotMessageCache.INSTANCE.getRobotMessageList(type,packageId);
        JSONObject body = new JSONObject();
        body.put("name", System.currentTimeMillis());// 图片name
        RobotMessage pic = picList.get((int) (Math.random() * picList.size()));
        try {
            URL url = new URL(pic.getMessage());
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            InputStream in = conn.getInputStream();
            BufferedImage sourceImg = ImageIO.read(in);
            int w = sourceImg.getWidth();
            int h = sourceImg.getHeight();
            body.put("md5", DigestUtils.md5Hex(in));// 图片文件md5
            body.put("url", pic.getMessage());
            String[] temp = pic.getMessage().split("\\.");
            body.put("ext", temp[temp.length - 1]);
            body.put("w", w);
            body.put("h", h);
            // 根据响应获取文件大小
            body.put("size", conn.getContentLength());
        } catch (Exception e) {
            logger.error("发送图片消息异常-md5转换错误：userId={},error={}", userId, e);
        }
        //获取一个随机主播
        List<Integer> userIds = new ArrayList<>();
        List<User> userList = userInfoDao.getUserListRand(5, userIds);
        User user = userList.get((int) (Math.random() * userList.size()));
        //开发者扩展字段
        JSONObject ext = new JSONObject();
        //ext开发者扩展字段-type类型：1文字，2免费图片，3付费图片，4视频
        //imagetype 1：免费 2：付费
        if(type == 2){
            ext.put("imagetype",1);
        }else{
            ext.put("imagetype",2);
        }
        try {
            logger.info("发送图片-云信：userId={},message={},ext={}", userId, body.toString(),ext.toString());
            String temp = NetEaseCloudUserService.getSendMsg(userId,user.getUserId(), 1, body.toString(),ext.toString(),"");
            if (!temp.substring(temp.indexOf("code") + 6, temp.indexOf("code") + 9).equals("200"))
                logger.error("发送图片消息异常-云信：userId={},message={}", userId, temp);
        } catch (Exception e) {
            logger.error("发送图片消息异常：userId={},error={}", userId, e);
        }
    }

    private void videoMessage(User user,int packageId){
        if(packageId ==2){
            //是否接听视频
            if (user.getIsVideo() == 2)
                return;
            //是否在线
            if (!lineTimeRedisDao.hasKeyLine(user.getUserId() + ""))
                return;
            //钱包是否有金币
            UserWallet userWallet = userInfoDao.getUserWalletById(user.getUserId());
            if(userWallet.getDeposit() >0)
                return;
        }
        if(user.getIsVideo() != 2){
            //随机获取要发送的内容
            List<RobotMessage> videoList = RobotMessageCache.INSTANCE.getRobotMessageList(4,packageId);
            //获取一个随机主播
            List<Integer> userIds = new ArrayList<>();
            List<User> userList = userInfoDao.getUserListRand(5, userIds);
            User robotUser = userList.get((int) (Math.random() * userList.size()));
            //开发者扩展字段
            JSONObject ext = new JSONObject();
            ext.put("videotype",1); //1:正常视频挂断需回复，2：弹窗视频，3：视频挂断不需回复
            String pushcontent = "向你申请视频通话";
            try {
                // 调用云信接口
                JSONObject body = new JSONObject();
                body.put("msg", videoList.get((int) (Math.random() * videoList.size())).getMessage());
                logger.info("发送视频type4-云信：userId={},message={},ext={}", user.getUserId(), body.toString(),ext.toString()+pushcontent);
                String temp = NetEaseCloudUserService.getSendMsg(user.getUserId(), robotUser.getUserId(), 100,
                        body.toString(),ext.toString(),pushcontent);
                if (!temp.substring(temp.indexOf("code") + 6, temp.indexOf("code") + 9).equals("200"))
                    logger.error("发送视频异常-云信：userId={},message={}", user.getUserId(), temp);
            } catch (Exception e) {
                logger.error("发送视频异常-系统：userId={},error={}", user.getUserId(), e);
            }
        }
    }

    private void vestTCYLVideoMessage(User user,int packageId){
        if(packageId ==2){
            //是否接听视频
            if (user.getIsVideo() == 2)
                return;
            //是否在线
            if (!lineTimeRedisDao.hasKeyLine(user.getUserId() + ""))
                return;
            //钱包是否有金币
            UserWallet userWallet = userInfoDao.getUserWalletById(user.getUserId());
            if(userWallet.getDeposit() >0)
                return;
        }
        //随机获取要发送的内容
        List<RobotMessage> videoList = RobotMessageCache.INSTANCE.getRobotMessageList(4,packageId);
        //获取一个随机主播
        List<Integer> userIds = new ArrayList<>();
        List<User> userList = userInfoDao.getUserListRand(5, userIds);
        User robotUser = userList.get((int) (Math.random() * userList.size()));
        //开发者扩展字段
        JSONObject ext = new JSONObject();
        ext.put("videotype",2); //1:正常视频挂断需回复，2：弹窗视频，3：视频挂断不需回复
        String pushcontent = "向你申请视频通话";
        try {
            // 调用云信接口
            JSONObject body = new JSONObject();
            body.put("msg", videoList.get((int) (Math.random() * videoList.size())).getMessage());
            logger.info("发送视频type5-云信：userId={},message={},ext={}", user.getUserId(), body.toString(),ext.toString()+pushcontent);
            String temp = NetEaseCloudUserService.getSendMsg(user.getUserId(), robotUser.getUserId(), 100,
                    body.toString(),ext.toString(),pushcontent);
            if (!temp.substring(temp.indexOf("code") + 6, temp.indexOf("code") + 9).equals("200"))
                logger.error("发送视频异常-云信：userId={},message={}", user.getUserId(), temp);
        } catch (Exception e) {
            logger.error("发送视频异常-系统：userId={},error={}", user.getUserId(), e);
        }

    }

}
